import { ref, onMounted, onUnmounted, watch, nextTick, getCurrentInstance } from 'vue'

export function useShowHide(el) {
    const visible = ref(false);
    const target = ref(null);




    //没有处理visibility='hidden',不可见但是占有空间的情况
    //只能处理 display=none, 方式的可见以否
    //el与body有交集就说明el可见，否则说明el不可见
    const observe = new IntersectionObserver(() => {
        visible.value = target.value.clientWidth > 0;
    }, {
        //root：body 无论是否在可见区域，只要有交集都能检测，
        //root: null | document, 只有可使口才会触发
        root: window.document.body
    });

    if (!el) {
        el = ref(null);

        onMounted(() => {
            let me = getCurrentInstance();
            el.value = me.ctx.$el || me.vnode.el;
        })
    }

    watch(el,
        () => {
            if (el.value) {
                target.value = el.value;
                visible.value = el.value.clientWidth > 0;
                observe.observe(el.value);
            }
        },
        { immediate: true, flush: 'post' });


    onUnmounted(() => {
        observe.disconnect();
    })

    return visible;
}